<template>
  <div>
    <div v-if="loading">
      视图数据加载中...
    </div>
    <div v-else>
      <div v-if="!hasInit">
        视图数据加载出现错误
      </div>
      <div v-else>
        <a-row :gutter="10">
          <a-col :span="showFilterView?0:3">
            <div :style="{border:'dashed 1px #333',padding:`10px`}">
              <draggable
                v-model="list"
                handle=".sortHandler"
                chosenClass="chosen"
                forceFallback="true"
                group="module"
                animation="1000"
                @end="onEnd">
                <transition-group>
                  <a-tag color="blue" class="wfull mb10 cpt" v-for="(c,i) in list" :key="`sort${i}`">
                    <i class="fa fa-arrows sortHandler cpt mr10"/>
                    {{ c.label?c.label:'条件名称' }}
                  </a-tag>
                </transition-group>
              </draggable>
            </div>
          </a-col>
          <a-col :span="showFilterView?24:21">
            <div v-if="showFilterView" class="pt30 pb30">
              <a-form :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                <a-row>
                  <a-col v-for="(c,i) in list" :key="`condition${i}`" :span="6">
                    <a-form-item :label="c.label">
                      <div v-if="c.condition==='between'">
                        <div v-if="c.compType==='日期'||c.compType==='日期时间'">
                          <ZgDateRangePicker></ZgDateRangePicker>
                        </div>
                        <div v-else class="flx-s">
                          <ZgNumber style="width:45%"></ZgNumber>
                          <div>&nbsp;至&nbsp;</div>
                          <ZgNumber style="width:45%"></ZgNumber>
                        </div>
                      </div>
                      <div v-else-if="['like'].includes(c.condition)">
                        <ZgInput></ZgInput>
                      </div>
                      <div v-else-if="['>','>=','<','<='].includes(c.condition)">
                        <div v-if="c.compType==='日期'">
                          <ZgDatePicker></ZgDatePicker>
                        </div>
                        <div v-else>
                          <ZgNumber></ZgNumber>
                        </div>
                      </div>
                      <div v-else>
                        <div v-if="c.compType==='日期'||c.compType==='日期时间'">
                          <ZgDatePicker></ZgDatePicker>
                        </div>
                        <div v-else-if="c.compType==='整数'">
                          <ZgNumber></ZgNumber>
                        </div>
                        <div v-else-if="c.compType==='字典'">
                          <ZgDictionary :code="c.extra.字典类型"></ZgDictionary>
                        </div>
                        <div v-else-if="['单选框','开关'].includes(c.compType)">
                          <ZgSelect :options="[{value:'是',label:'是'},{value:'否',label:'否'}]"></ZgSelect>
                        </div>
                        <div v-else>
                          <ZgInput></ZgInput>
                        </div>
                      </div>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <a-table v-if="!showFilterView&&columns.length>0" :data-source="list">
              <a-table-column title="过滤字段">
                <template slot-scope="text,record">
                  <ZgSelect v-model="record.name" @change="onColumnChange($event,record)" :options="columns.map(t=>{return {value:t.name,label:t.name}})"></ZgSelect>
                </template>
              </a-table-column>
              <a-table-column title="字段编码" dataIndex="code"></a-table-column>
              <a-table-column title="字段类型" dataIndex="compType"></a-table-column>
              <a-table-column :width="200" title="应用函数">
                <template slot-scope="text,record">
                  <ZgInput v-model="record.fun" placeholder="例如：to_char(#)"></ZgInput>
                </template>
              </a-table-column>
              <a-table-column :width="240" title="选择条件">
                <template slot-scope="text,record">
                  <div class="flx-s">
                    <ZgSelect v-model="record.condition" :options="getOpts(record.compType)"></ZgSelect>
                  </div>
                </template>
              </a-table-column>
              <a-table-column :width="160" title="条件名称">
                <template slot-scope="text,record">
                  <ZgInput v-model="record.label"></ZgInput>
                </template>
              </a-table-column>
              <a-table-column :width="120" title="操作">
                <template slot-scope="text,record,index">
                  <a-button @click="plus(index)" shape="circle" class="mr10"><i class="fa fa-plus"/></a-button>
                  <a-button @click="minus(index)" shape="circle"><i class="fa fa-minus"/></a-button>
                </template>
              </a-table-column>
            </a-table>
            <div class="mt10 flx-e">
              <a-button class="mr10" @click="plus(-1)">
                <i class="fa fa-plus mr5"/>添加字段
              </a-button>
              <a-button class="mr10" @click="toggleCondition">
                <span v-if="showFilterView"><i class="fa fa-minus-circle mr5"/>取消预览</span>
                <span v-else><i class="fa fa-eye mr5"/>预览</span>
              </a-button>
              <a-button class="mr10" @click="search">
                <i class="fa fa-refresh mr5"/>刷新
              </a-button>
              <a-button type="primary" @click="save">
                <i class="fa fa-check mr5"/>保存视图
              </a-button>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
  components: {
    draggable
  },
  props: {
    formId: {
      type: String,
      default: '0'
    }
  },
  data () {
    return {
      hasInit: false,
      loading: false,
      showFilterView: false,
      hasNot: false,
      columns: [],
      list: [],
      extra: {
        枚举编码: '',
        字典类型: ''
      }
    }
  },
  watch: {
    formId () {
      this.search()
    }
  },
  mounted () {
    this.search()
  },
  methods: {
    getOpts (type) {
      let arr = []
      if (['整数', '浮点数', '日期', '日期时间'].includes(type)) {
        arr = ['between', '=', '>', '>=', '<', '<=']
      } else if (['单选框', '开关', '字典'].includes(type)) {
        arr = ['=']
      } else if (['多选'].includes(type)) {
        arr = ['like']
      } else {
        arr = ['=', 'like']
      }
      return arr.map(t => {
        return {
          label: t,
          value: t
        }
      })
    },
    search () {
      this.hasInit = false
      this.loading = true
      const timer = setTimeout(() => {
        this.loading = false
      }, 30000)
      this.$http.get('/zg-autoform/filter/layout', { formId: this.formId }, data => {
        this.columns = data[0].map(t => {
          try {
            t.extra = Object.assign({}, this.extra, JSON.parse(t.extra))
          } catch (e) {
            t.extra = JSON.parse(JSON.stringify(this.extra))
          }
          return t
        })
        this.list = data[1].filter(t => {
          const arr = this.columns.filter(x => {
            return x.id === t.columnId
          })
          return arr.length > 0
        }).map(t => {
          const arr = this.columns.filter(x => {
            return x.id === t.columnId
          })
          return Object.assign({}, t, {
            id: arr[0].id,
            key: arr[0].id,
            name: arr[0].name,
            code: arr[0].code,
            compType: arr[0].compType,
            extra: arr[0].extra
          })
        })
        this.$nextTick(() => {
          this.columns.sort((a, b) => {
            return a.sort - b.sort
          })
          clearTimeout(timer)
          this.hasInit = true
          this.loading = false
        })
      })
    },
    save () {
      if (this.list.some(t => {
        return t.id.length === 0 || t.condition.length === 0 || t.label.length === 0
      })) {
        this.$warning({ title: '请完整设置每个过滤条件的信息' })
      } else {
        const conditionList = this.list.map(t => {
          return {
            formId: this.formId,
            columnId: t.id,
            columnCode: t.code,
            columnType: t.compType,
            fun: t.fun,
            hasNot: t.hasNot,
            type: t.condition,
            label: t.label,
            sort: t.sort
          }
        })
        const param = {
          formId: this.formId,
          conditionList: conditionList
        }
        this.$http.post('/zg-autoform/filter/layout/update', param, (count) => {
          this.$success({ title: `过滤器视图保存成功，共${count}个条件` })
        })
      }
    },
    plus (i) {
      this.list.splice(i + 1, 0, {
        id: '',
        name: '',
        code: '',
        compType: '',
        fun: '',
        hasNot: false,
        condition: '',
        label: '',
        sort: 0,
        extra: {
          枚举编码: '',
          字典类型: ''
        }
      })
    },
    minus (i) {
      this.list.splice(i, 1)
    },
    onColumnChange (name, obj) {
      if (!name || name.length === 0) {
        return
      }
      const arr = this.columns.filter(t => {
        return t.name === name
      })
      obj.id = arr[0].id
      obj.code = arr[0].code
      obj.compType = arr[0].compType
      if (obj.label.length === 0) {
        obj.label = arr[0].name
      }
      if (['整数', '浮点数'].includes(obj.compType)) {
        obj.condition = 'between'
        obj.fun = 'to_number(#)'
      } else if (['日期', '日期时间'].includes(obj.compType)) {
        obj.condition = 'between'
      } else if (['多选'].includes(obj.compType)) {
        obj.condition = 'like'
      } else {
        obj.condition = '='
      }
      obj.extra = arr[0].extra
    },
    toggleCondition () {
      this.showFilterView = !this.showFilterView
    },
    onEnd () {
      this.saving = true
      this.list.forEach((t, i) => {
        t.sort = i + 1
      })
      this.saving = false
    }
  }
}
</script>

<style lang="scss" scoped>
.chosen{
  border:solid 1px #096daf;
  background:#096daf;
  color:#fff;
}
</style>
